import {
  addFriendsApi,
  agreeRequestApi,
  createGroupApi,
  getMyAddMsgApi,
  refuseRequestApi
} from "@/api/api_chatSocket/chatSocket_Api";
import type { Ref } from "vue";
import { sendSocketMsg } from "@/websocket/socket-io";

// 添加好友
export const addFriendFunc = () => {
  const searchText: Ref<string> = ref("");
  const addFriend = async (searchText: string): Promise<void> => {
    if (!searchText) {
      ElMessage.error("请输入用户账号！");
      return;
    }
    let addFriendResult = await addFriendsApi(searchText, 0);
    ElMessage.success(addFriendResult.data.msg);
  };
  return [searchText, addFriend];
};

// 加入群聊
export const joinGroupFunc = () => {
  const joinGroupText: Ref<string> = ref("");
  const joinGroup = async (joinGroupText: string): Promise<void> => {
    if (!joinGroupText) {
      ElMessage.error("请输入群聊账号！");
      return;
    }
    let addFriendResult = await addFriendsApi(joinGroupText, 1);
    ElMessage.success(addFriendResult.data.msg);
  };
  return [joinGroupText, joinGroup];
};

// 创建群聊
export const createGroupFunc = () => {
  const newGroupName: Ref<string> = ref("");
  const createGroup = async (newGroupName: string): Promise<void> => {
    if (!newGroupName) {
      ElMessage.error("请输入群名称！");
      return;
    }
    await createGroupApi(newGroupName);
  };
  return [newGroupName, createGroup];
};

//获取请求列表
export const getRequestListFunc = () => {
  const requestList: Ref<userAddMsgType[]> = ref([]);
  const getRequestList = async (): Promise<void> => {
    let getListResult = await getMyAddMsgApi();
    if (getListResult.data.msg.requestList.count !== 0) {
      requestList.value = getListResult.data.msg.requestList.rows.filter((item: any) => {
        return item._receiver_account === localStorage["account"];
      });
    }
  };
  return [requestList, getRequestList];
};

//同意请求
export const agreeRequest = async (senderAccount: string, type: number, receiverAccount?: string, sessionID?: string): Promise<void> => {
  await agreeRequestApi(senderAccount, type, receiverAccount, sessionID);
};

//拒绝请求
export const refuseRequest = async (senderAccount: string, type: number, receiverAccount?: string, sessionID?: string): Promise<void> => {
  await refuseRequestApi(senderAccount, type, receiverAccount, sessionID);
};

//显示是否同意请求 对话框
export const requestAlertFunc = () => {
  const showElMessage: Ref<boolean> = ref(false);
  const onOk: Ref<any> = ref(() => {
  });
  const onCancel: Ref<any> = ref(() => {
    onOk.value = () => {
    };
    showElMessage.value = false;
    ElMessageContent.value = "";
  });
  const ElMessageContent: Ref<string> = ref("");
  const showRequestElMessage = (item: userAddMsgType, callBack: Function) => {
    if (item._result) return;
    if (item._add_type) {
      ElMessageBox({
        distinguishCancelAndClose: true,
        showCancelButton: true,
        title: "加入群聊申请",
        message: `是否同意${item._sender_account}加入群组${item._session_id}`,
        callback: (action: string) => {
          if (action === "confirm") {
            agreeRequest(item._sender_account, item._add_type, item._receiver_account, item._session_id).then(_ => callBack());
          } else if (action === "cancel") {
            refuseRequest(item._sender_account, item._add_type, item._receiver_account, item._session_id).then(_ => callBack());
          }
        }
      });
      return;
    }
    ElMessageBox({
      distinguishCancelAndClose: true,
      showCancelButton: true,
      title: "加入群聊申请",
      message: `是否同意${item._sender_account}加您为好友`,
      callback: (action: string) => {
        if (action === "confirm") {
          agreeRequest(item._sender_account, item._add_type, item._receiver_account, item._session_id).then(_ => callBack());
        } else if (action === "cancel") {
          refuseRequest(item._sender_account, item._add_type, item._receiver_account, item._session_id).then(_ => callBack());
        }
      }
    });
    return;
  };
  return [showRequestElMessage];
};

//发送消息
export const sendMessageFunc = () => {
  const message: Ref<string> = ref("");
  const sendSocketMessage = () => {
    let msgTo: msgToType = localStorage["msgToUser"] ? JSON.parse(localStorage["msgToUser"]) : {};
    if (!(msgTo.sessionID && message.value)) {
      ElMessage.info("请先选择发送对象和消息");
      return;
    }
    sendSocketMsg("message", {
      ...msgTo,
      message: message.value,
      timestamp: new Date().getTime()
    });
  };
  return [message, sendSocketMessage];
};

//设置发送消息对象
export const setMessageOwner = () => {
  const msgToServer: Ref<msgToType> = ref(JSON.parse(localStorage["msgToUser"] || "{}"));
  const setSendUser = (item: joinListItemType) => {
    const msgTo: msgToType = {
      type: item._type,
      sender: localStorage["account"],
      sessionID: item._session_id
    };
    msgToServer.value = msgTo;
    localStorage["msgToUser"] = JSON.stringify(msgTo);
    ElMessage.success(`设置成功。对象为${msgTo.type ? "群聊" : "个人"}`);
  };
  return [msgToServer, setSendUser];
};

// 消息的选中对象sessionid
const sessionIdSelected:Ref<string> = ref('');

export const sessionIdSelectedFunc = ():[(() => Ref<string>), ((id: string) => void)] => {
  const get = ():Ref<string> => {
    return sessionIdSelected;
  }
  const set = (id:string):void => {
    sessionIdSelected.value = id;
  }
  return [get, set];
};
// 消息的选中对象类型 0好友 1群聊
const selectedType:Ref<number> = ref(0);
export const selectedTypeFunc = ():[(() => Ref<number>), ((type: number) => void)] => {
  const get = ():Ref<number> => {
    return selectedType;
  }
  const set = (type:number):void => {
    selectedType.value = type;
  }
  return [get, set];
};

// 更新选中的session_id和type
export const updateSelectedFunc = (id:string, type:number) => {
  sessionIdSelected.value = id;
  selectedType.value = type;
}


